<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Cache\CacheServiceProvider;
use Illuminate\Database\DatabaseServiceProvider;
use Illuminate\Foundation\Providers\ConsoleSupportServiceProvider;
use Illuminate\View\ViewServiceProvider;
use Illuminate\Foundation\Providers\FoundationServiceProvider;
use Illuminate\Translation\TranslationServiceProvider;

class SqlLogServiceProvider extends ServiceProvider
{
    public function register()
    {
        // 添加加密服务提供者到最前面
        $this->app->register(\Illuminate\Encryption\EncryptionServiceProvider::class);
        
        $this->app->register(FoundationServiceProvider::class);
        $this->app->register(TranslationServiceProvider::class);
        $this->app->register(ViewServiceProvider::class);
        $this->app->register(ConsoleSupportServiceProvider::class);
        $this->app->register(CacheServiceProvider::class);
        $this->app->register(DatabaseServiceProvider::class);
        $this->app->singleton('files', function () {
            return new Filesystem;
        });
    }

    public function boot()
    {
        DB::listen(function ($query) {
            $sql = str_replace(['?'], ['\'%s\''], $query->sql);
            $fullSql = vsprintf($sql, $query->bindings);
            
            Log::channel('sql')->debug("[SQL] {$fullSql}", [
                // 'time' => $query->time.'ms',
                // 'connection' => $query->connectionName
            ]);
        });
    }
}
